﻿// MIT License
// 开源地址：https://gitee.com/co1024/AbcMvc
// Copyright (c) 2021-2022 1024
// Abc.Mvc=Furion+EF+SqlSugar+Pear layui admin.

namespace Abc.Core;

public static class SqlSugarCore
{
    #region 获取数据库连接配置，AOP

    /// <summary>
    /// 获取数据库连接配置
    /// </summary>
    /// <returns></returns>
    public static List<ConnectionConfig> GetConnectionConfig()
    {
        return SqlSugarDbSetting.ConnectionConfigs;
    }

    /// <summary>
    /// 缓存 sqlsugar 数据库配置 选项
    /// </summary>
    public static SqlSugarDbSettingOptions SqlSugarDbSetting => GetSqlSugarDbSettingOptions();

    /// <summary>
    /// 获取 SqlSugarDbSetting Options
    /// </summary>
    /// <returns></returns>
    public static SqlSugarDbSettingOptions GetSqlSugarDbSettingOptions()
    {
        //if (SqlSugarDbSetting != null) return SqlSugarDbSetting;
        var sqlSugarDbSetting = AppEx.GetConfig<SqlSugarDbSettingOptions>();
        foreach (var conn in sqlSugarDbSetting.ConnectionConfigs)
        {
            conn.ConfigureExternalServices = GetConfigureExternalServices(sqlSugarDbSetting, conn);
            conn.MoreSettings = new ConnMoreSettings()
            {
                //所有 增、删 、改 会自动调用.RemoveDataCache()
                //意思就是 增、删 、改 都会移除对应表数据的 sqlsugar缓存
                IsAutoRemoveDataCache = true,

                //MySql禁用NVarchar
                DisableNvarchar = conn.DbType == DbType.MySql ? true : false
            };
        }
        //SqlSugarDbSetting = sqlSugarDbSetting;
        return sqlSugarDbSetting;
    }

    /// <summary>
    /// ConfigureExternalServices
    /// </summary>
    /// <returns></returns>
    public static ConfigureExternalServices GetConfigureExternalServices(SqlSugarDbSettingOptions sqlSugarDbSetting, ConnectionConfig conn)
    {
        ICacheService sqlSugarCache = new SqlSugarDistributedCache();
        return new ConfigureExternalServices
        {
            DataInfoCacheService = sqlSugarCache, //配置我们创建的缓存类，具体用法看标题5
            EntityService = (property, column) =>
            {
                var attributes = property.GetCustomAttributes(true);//get all attributes

                var sugarColumnAttribute = attributes.FirstOrDefault(o => o is SugarColumn);
                if (sugarColumnAttribute != null)
                {
                    //这里是sqlsugar的设置。。暂时没有。。
                }
                else
                {
                    //设置，标记了 Key 属性的字段为主键
                    var keyAttribute = attributes.FirstOrDefault(o => o is KeyAttribute);
                    if (keyAttribute != null)
                    {
                        column.IsPrimarykey = true; //有哪些特性可以看 1.2 特性明细
                    }
                }

                ////数据库没有进行初始化的时候才设置为自增
                ////必须是ID字段才执行，中间表可能会设置为自增，出现问题
                ////【 因为使用了 IsPrimarykey 所以得放到上面的代码后面 】
                //if (column.DbColumnName != null && column.DbColumnName.ToUpper() == "ID"
                //&& column.IsPrimarykey == true && column.IsIdentity == false
                ////&& sqlSugarDbSetting.EnableInitDatabase == false
                //&& (sqlSugarDbSetting.NoIsIdentityDbTables == null || !sqlSugarDbSetting.NoIsIdentityDbTables.All(a => a.ToLower() != column.DbTableName.ToLower()))
                //)
                //{
                //    //设置自增
                //    column.IsIdentity = sqlSugarDbSetting.EntityIsIdentity;
                //}

                // 未设置 SugarColumn 的字段，设置字符串（string）默认可以为空
                if (column.PropertyInfo.PropertyType.Name == nameof(System.String))
                {
                    if (attributes.All(it => it is not SugarColumn))
                    {
                        //默认都把字符串设置为可空
                        column.IsNullable = true;
                        column.Length = 500;//设置字符串默认的长度
                    }
                    else
                    {
                        //表示有贴  SugarColumn 标签
                        var sugarColumn = (SugarColumn)attributes.FirstOrDefault(it => it is SugarColumn);
                        //自定ColumnDataType格式的情况 length不要设置
                        if (sugarColumn.Length <= 0 && string.IsNullOrWhiteSpace(sugarColumn.ColumnDataType))
                        {
                            column.Length = 500;//设置字符串默认的长度
                        }
                    }

                    var columnAttribute = attributes.FirstOrDefault(o => o is ColumnAttribute);
                    //判断是否贴了 Column 属性
                    if (columnAttribute != null)
                    {
                        //设置自定义的TypeName
                        //[Column(TypeName = "decimal(18,2)")]
                        //public decimal Payment { get; set; }
                        column.DataType = ((ColumnAttribute)columnAttribute).TypeName;
                    }



                    //判断是否设置了字符串的 MaxLength  自动设置
                    var maxLengthAttribute = attributes.FirstOrDefault(o => o is MaxLengthAttribute);
                    //设置了 DataType格式的情况 length不要设置
                    if (maxLengthAttribute != null && string.IsNullOrWhiteSpace(column.DataType))
                    {
                        var attr = (MaxLengthAttribute)maxLengthAttribute;

                        if (attr.Length <= 0)
                        {
                            column.Length = 500;//设置字符串默认的长度
                        }
                        else
                        {
                            column.Length = attr.Length;
                        }
                    }
                }

                // int?  decimal?这种 isnullable=true
                if (column.IsNullable == false && property.PropertyType.IsGenericType &&
                property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                {
                    column.IsNullable = true;
                }
            },
            //这个是设置数据库表的名称的，例如，实体叫“User” 数据库叫“Sys_User”
            //解析了 EF的 Table 属性
            EntityNameService = (type, entity) =>
            {
                var attributes = type.GetCustomAttributes(true);
                if (attributes.Any(it => it is TableAttribute))
                {
                    var attr = attributes.FirstOrDefault(it => it is TableAttribute);
                    if (attr != null)
                    {
                        var tableAttribute = (TableAttribute)attr;
                        entity.DbTableName = tableAttribute.Name;
                    }

                    //entity.DbTableName = (attributes.First(it => it is TableAttribute) as TableAttribute).Name;
                }
            }
        };
    }

    public static void SqlSugarClientAction(this SqlSugarClient db)
    {
        SqlSugarDbSetting.ConnectionConfigs.ForEach(config =>
        {
            ////配置
            //db.SqlSugarConfig((string)config.ConfigId);
            var dbProvider = db.GetConnectionScope((string)config.ConfigId);
            // 设置超时时间
            dbProvider.Ado.CommandTimeOut = 30;

            //每次Sql执行前事件
            dbProvider.SqlSugar_OnLogExecuting(db);
            //SQL执行完
            dbProvider.SqlSugar_OnLogExecuted(db);
            //可以修改SQL和参数的值
            dbProvider.SqlSugar_OnExecutingChangeSql(db);
            //SQL报错
            dbProvider.SqlSugar_OnError(db);
            // 差异日志功能
            dbProvider.SqlSugar_OnDiffLogEvent(db);
            //插入和更新过滤器
            dbProvider.SqlSugar_DataExecuting(db);
            //全局过滤器
            dbProvider.SqlSugar_Filter(db);
        });
    }

    /// <summary>
    /// 设置 sqlsugar config
    /// </summary>
    /// <param name="db"></param>
    /// <param name="configId"></param>
    public static void SqlSugarConfig(this SqlSugarClient db, string configId = "Abc")
    {
        var dbProvider = db.GetConnectionScope(configId);
        dbProvider.SqlSugarConfig(db);
    }

    public static void SqlSugarConfig(this SqlSugarScopeProvider dbProvider, SqlSugarClient db)
    {
        ////(A)全局生效配置点
        ////调试SQL事件，可以删掉
        //db.Aop.OnLogExecuting = (sql, pars) =>
        //{
        //    Console.WriteLine(sql);//输出sql,查看执行sql
        //                           //5.0.8.2 获取无参数化 SQL
        //                           //UtilMethods.GetSqlString(DbType.SqlServer,sql,pars)
        //};
        // 设置超时时间
        dbProvider.Ado.CommandTimeOut = 30;

        //每次Sql执行前事件
        dbProvider.SqlSugar_OnLogExecuting(db);
        //SQL执行完
        dbProvider.SqlSugar_OnLogExecuted(db);
        //可以修改SQL和参数的值
        dbProvider.SqlSugar_OnExecutingChangeSql(db);
        //SQL报错
        dbProvider.SqlSugar_OnError(db);
        // 差异日志功能
        dbProvider.SqlSugar_OnDiffLogEvent(db);
        //插入和更新过滤器
        dbProvider.SqlSugar_DataExecuting(db);
        //全局过滤器
        dbProvider.SqlSugar_Filter(db);
    }

    /// <summary>
    /// 可以修改SQL和参数的值
    /// </summary>
    /// <param name="sql"></param>
    /// <param name="pars"></param>
    /// <returns></returns>
    public static void SqlSugar_OnExecutingChangeSql(this SqlSugarScopeProvider dbProvider, SqlSugarClient db)
    {
        dbProvider.Aop.OnExecutingChangeSql = (sql, pars) =>
        {
            //var _logger = AppEx.GetLogger("SqlSugar\\修改SQL和参数的值");
            //sql=newsql
            //foreach(var p in pars) //修改
            return new KeyValuePair<string, SugarParameter[]>(sql, pars);
        };
    }

    /// <summary>
    /// 每次Sql执行前事件
    /// </summary>
    /// <param name="sql"></param>
    /// <param name="pars"></param>
    public static void SqlSugar_OnLogExecuting(this SqlSugarScopeProvider dbProvider, SqlSugarClient db)
    {
        dbProvider.Aop.OnLogExecuting = (sql, pars) =>
        {

            //5.0.8.2 获取无参数化 SQL
            var sqlStr = UtilMethods.GetSqlString(db.CurrentConnectionConfig.DbType, sql, pars);

            var sqlSugarDbSetting = AppEx.GetConfig<SqlSugarDbSettingOptions>();
            if (sqlSugarDbSetting.IsRecordExecSql == true)
            {
                var _logger = AppEx.GetLogger("SqlSugar\\每次Sql执行前事件");
                //Console.WriteLine(sql);//输出sql,查看执行sql


                _logger.Debug($"执行SQL:{sqlStr}");
            }

            #region 控制台打印

            if (sql.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
                Console.ForegroundColor = ConsoleColor.Green;
            if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase))
                Console.ForegroundColor = ConsoleColor.White;
            if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase))
                Console.ForegroundColor = ConsoleColor.Blue;
            Console.WriteLine("【" + DateTime.Now + "——执行SQL】\r\n" + sqlStr + "\r\n");

            App.PrintToMiniProfiler("SqlSugar", "Info", sqlStr);

            #endregion 控制台打印
        };
    }

    /// <summary>
    /// SQL执行完
    /// </summary>
    /// <param name="dbProvider"></param>
    /// <param name="db"></param>
    public static void SqlSugar_OnLogExecuted(this SqlSugarScopeProvider dbProvider, SqlSugarClient db)
    {
        dbProvider.Aop.OnLogExecuted = (sql, pars) =>
        {
            //执行时间超过1秒
            if (db.Ado.SqlExecutionTime.TotalSeconds > 1)
            {
                //代码CS文件名
                var fileName = db.Ado.SqlStackTrace.FirstFileName;
                //代码行数
                var fileLine = db.Ado.SqlStackTrace.FirstLine;
                //方法名
                var FirstMethodName = db.Ado.SqlStackTrace.FirstMethodName;
                //db.Ado.SqlStackTrace.MyStackTraceList[1].xxx 获取上层方法的信息

                var _logger = AppEx.GetLogger("SqlSugar\\SQL执行时间超过1秒事件");
                _logger.Debug($"代码cs文件夹名：{fileName}\r\n 代码行数：{fileLine}\r\n 方法名：{FirstMethodName}\r\nsql:{sql}\r\n参数：{pars.ToJson()}");
            }
        };
    }

    /// <summary>
    /// 差异日志功能
    /// </summary>
    /// <param name="dbProvider"></param>
    /// <param name="db"></param>
    public static void SqlSugar_OnDiffLogEvent(this SqlSugarScopeProvider dbProvider, SqlSugarClient db)
    {
        //差异日志功能
        //Sql执行完后会进该事件，该事件可以拿到更改前记录和更改后记录，执行时间等参数（可以监控表变动）
        db.Aop.OnDiffLogEvent = (diffLogModel) =>
        {
            var sqlSugarDbSetting = AppEx.GetConfig<SqlSugarDbSettingOptions>();
            if (sqlSugarDbSetting.EnableDiffLog == false) return;
            ////操作前记录  包含： 字段描述 列名 值 表名 表描述
            //var editBeforeData = it.BeforeData;//插入Before为null，之前还没进库
            ////操作后记录   包含： 字段描述 列名 值  表名 表描述
            //var editAfterData = it.AfterData;
            //var sql = it.Sql;
            //var parameter = it.Parameters;
            //var data = it.BusinessData;//这边会显示你传进来的对象
            //var time = it.Time;
            //var diffType = it.DiffType;//enum insert 、update and delete

            ////Write logic
            //var _logger = AppEx.GetLogger("SqlSugar\\差异日志", retainedFileCountLimit: 20, fileSizeLimitBytes: 100 * 1024 * 1024);
            //_logger.Debug($"sql:{sql}\r\n参数：{parameter.ToJson()}\\操作类型：{diffType:G}\r\n传进来的对象：{data.ToJson()}\r\n执行时间:{time?.TotalSeconds}");

            //var logDiff = new SysLogDiff
            //{
            //    // 操作后记录（字段描述、列名、值、表名、表描述）
            //    AfterData = JsonConvert.SerializeObject(diffLogModel.AfterData),
            //    // 操作前记录（字段描述、列名、值、表名、表描述）
            //    BeforeData = JsonConvert.SerializeObject(diffLogModel.BeforeData),
            //    // 传进来的对象
            //    BusinessData = JsonConvert.SerializeObject(diffLogModel.BusinessData),
            //    // 枚举（insert、update、delete）
            //    DiffType = diffLogModel.DiffType.ToString(),
            //    Sql = UtilMethods.GetSqlString(DbType.MySql, diffLogModel.Sql, diffLogModel.Parameters),
            //    Parameters = JsonConvert.SerializeObject(diffLogModel.Parameters),
            //    Duration = diffLogModel.Time == null ? 0 : (int)diffLogModel.Time.Value.TotalMilliseconds
            //};
            //EventBusCenter.Instance.EventPublisher(EventSubscribeType.异常日志, logDiff);

            //Console.ForegroundColor = ConsoleColor.Red;
            //Console.WriteLine(DateTime.Now + $"\r\n**********差异日志开始**********\r\n{Environment.NewLine}{JsonConvert.SerializeObject(logDiff)}{Environment.NewLine}**********差异日志结束**********\r\n");
        };
    }

    /// <summary>
    /// SQL报错
    /// </summary>
    /// <param name="dbProvider"></param>
    /// <param name="db"></param>
    public static void SqlSugar_OnError(this SqlSugarScopeProvider dbProvider, SqlSugarClient db)
    {
        dbProvider.Aop.OnError = (exp) =>
        {
            try
            {
                #region 控制台打印

                Console.ForegroundColor = ConsoleColor.Red;
                //var pars = db.Utilities.SerializeObject(((SugarParameter[])exp.Parametres).ToDictionary(it => it.ParameterName, it => it.Value));
                var pars = "";
                Console.WriteLine("【" + DateTime.Now + "——错误SQL】\r\n" + UtilMethods.GetSqlString(db.CurrentConnectionConfig.DbType, exp.Sql, (SugarParameter[])exp.Parametres) + "\r\n");
                App.PrintToMiniProfiler("SqlSugar", "Error", $"{exp.Message}{Environment.NewLine}{exp.Sql}{pars}{Environment.NewLine}");

                #endregion 控制台打印


                //exp.sql 这样可以拿到错误SQL
                //5.0.8.2 获取无参数化 SQL
                //UtilMethods.GetSqlString(DbType.SqlServer,exp.sql,exp.parameters)
                var _logger = AppEx.GetLogger("SqlSugar\\SQL错误日志");

                var sqlStr = UtilMethods.GetSqlString(db.CurrentConnectionConfig.DbType, exp.Sql, (SugarParameter[])exp.Parametres);

                _logger.Error($"Source:{exp.Source}\r\nSQL：{sqlStr}\r\nStackTrace:{exp.StackTrace}\r\nInnerException:{exp.InnerException.ToStringEx()}");
            }
            catch (Exception ex)
            {
            }
        };
    }

    /// <summary>
    /// 插入和更新过滤器
    /// </summary>
    /// <param name="dbProvider"></param>
    /// <param name="db"></param>
    public static void SqlSugar_DataExecuting(this SqlSugarScopeProvider dbProvider, SqlSugarClient db)
    {
        dbProvider.Aop.DataExecuting = (oldValue, entityInfo) =>
        {
            //这样每条记录就只执行一次
            // SqlSugarCustomerCacheCenter.DataFilter(entityInfo);
            //entityInfo 有字段所有参数
            var _logger = AppEx.GetLogger("SqlSugar\\插入和更新过滤器");
            //兼容其它ORM AOP写法
            //SqlSugar是通过每行记录每个值进行的细粒度AOP,如果一行数据只想进一次事件
            if (entityInfo.EntityColumnInfo.IsPrimarykey) //通过主键保证只进一次事件
            {
                #region inset生效

                //判断是否是自增，不是自增就使用雪花ID，必须是int类型
                //if (entityInfo.EntityColumnInfo.IsIdentity == false && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType.Name == nameof(System.32))
                //{
                //    var id = entityInfo.EntityValue.GetFieldValue<int>("Id");
                //    if (id <= 0)
                //    {
                //        //SetFiledValue(entityInfo, "Id", SnowFlakeSingle.Instance.NextId());
                //        SetFiledValue(entityInfo, "Id", YitIdHelper.NextId());
                //    }
                //}

                if (entityInfo.OperationType == DataFilterType.InsertByObject)
                {
                    SetFiledValue(entityInfo, "CreatorUserId", App.HttpContext.GetLoginUserId<int>());
                    SetFiledValue(entityInfo, "CreatorUserName", App.HttpContext.GetLoginUserAccount());
                    SetFiledValue(entityInfo, "CreationTime", DateTimeOffset.Now);
                }

                #endregion inset生效

                #region update生效

                if (entityInfo.OperationType == DataFilterType.UpdateByObject)
                {
                    //是否逻辑删除(假删除)
                    //if (entityInfo.PropertyName == "IsDeleted")
                    //{
                    var properyDate = entityInfo.EntityValue.GetType().GetProperty("IsDeleted");
                    //判断是否有 IsDeleted字段，如果有才执行下面代码，否则会报错
                    if (properyDate != null)
                    {
                        var isdeleted = properyDate.GetValue(entityInfo.EntityValue, null).To<bool>();
                        if (isdeleted)
                        {
                            SetFiledValue(entityInfo, "DeletedUserId", App.HttpContext.GetLoginUserId<int>());
                            SetFiledValue(entityInfo, "DeletedUserName", App.HttpContext.GetLoginUserAccount());
                            SetFiledValue(entityInfo, "DeletedTime", DateTimeOffset.Now);
                        }
                        else
                        {
                            SetUpdateInfo(entityInfo);
                        }
                    }
                    else
                    {
                        SetUpdateInfo(entityInfo);
                    }

                    static void SetUpdateInfo(DataFilterModel entityInfo)
                    {
                        SetFiledValue(entityInfo, "UpdateUserId", App.HttpContext.GetLoginUserId<int>());
                        SetFiledValue(entityInfo, "UpdateUserName", App.HttpContext.GetLoginUserAccount());
                        SetFiledValue(entityInfo, "UpdateTime", DateTimeOffset.Now);
                    }
                }

                #endregion update生效
            }

            //设置指定字段的值
            static void SetFiledValue(DataFilterModel entityInfo, string filedName, object value)
            {
                var properyInfo = entityInfo.EntityValue.GetType().GetProperty(filedName);
                if (properyInfo != null)
                {
                    properyInfo.SetValue(entityInfo.EntityValue, value);
                }
            }

            //根据当前列修改另一列 可以么写
            //if(当前列逻辑==XXX)
            //var properyDate = entityInfo.EntityValue.GetType().GetProperty("Date");
            //if(properyDate!=null)
            //properyDate.SetValue(entityInfo.EntityValue,1);
        };
    }

    /// <summary>
    /// 全局过滤器
    /// </summary>
    /// <param name="db"></param>
    public static void SqlSugar_Filter(this SqlSugarScopeProvider dbProvider, SqlSugarClient db)
    {
        var _logger = AppEx.GetLogger("SqlSugar\\全局过滤器");
        List<Type> types = App.EffectiveTypes.Where(a => !a.IsAbstract && a.IsClass && a.GetCustomAttributes(typeof(SugarTable), true)?.FirstOrDefault() != null).ToList();

        foreach (var entityType in types)
        {
            //// 配置多租户全局过滤器
            //if (!entityType.GetProperty("TenantId").IsEmpty())
            //{ //判断实体类中包含TenantId属性
            //  //构建动态Lambda
            //    var lambda = DynamicExpressionParser.ParseLambda
            //    (new[] { Expression.Parameter(entityType, "it") },
            //     typeof(bool), $"{nameof(EntityTenantBase.TenantId)} ==  @0 or (@1 and @2)",
            //      GetTenantId(), IsSuperAdmin(), superAdminViewAllData);
            //    db.QueryFilter.Add(new TableFilterItem<object>(entityType, lambda)); //将Lambda传入过滤器
            //}

            //if (!typeof(IDeleted).IsAssignableFrom(entityType)) continue;

            // 配置加删除全局过滤器
            var deletePropertyInfo = entityType.GetProperty("IsDeleted");
            if (deletePropertyInfo != null && !deletePropertyInfo.IsEmpty())
            { //判断实体类中包含IsDeleted属性
              //构建动态Lambda
                var lambda = DynamicExpressionParser.ParseLambda
                (new[] { Expression.Parameter(entityType, "it") },
typeof(bool), $"{nameof(IDeleted.IsDeleted)} ==  @0",
                  false);
                db.QueryFilter.Add(new TableFilterItem<object>(entityType, lambda)
                {
                    IsJoinQuery = true
                }); //将Lambda传入过滤器
            }
        }

        ////全局过滤器
        //db.QueryFilter
        //.Add(new SqlFilterItem()//单表全局过滤器
        //{
        //    FilterValue = filterDb =>
        //    {
        //        return new SqlFilterResult() { Sql = " isDeleted=0" };
        //    },
        //    IsJoinQuery = false
        //}).Add(new SqlFilterItem()//多表全局过滤器
        //{
        //    FilterValue = filterDb =>
        //    {
        //        return new SqlFilterResult() { Sql = " f.isDeleted=0" };
        //    },
        //    IsJoinQuery = true
        //});
        //.Add(new SqlFilterItem() //qurery1过滤器
        //{
        //    FilterName = "query1",
        //    FilterValue = filterDb =>
        //    {
        //        return new SqlFilterResult() { Sql = " id>@id", Parameters = new { id = 1 } };
        //    },
        //    IsJoinQuery = false
        //});
    }

    /// <summary>
    /// sqlsugar数据改变监听(未测试，待细化功能)
    /// </summary>
    /// <param name="db">DBL连接</param>
    /// <param name="diffLogModel">差异日志模型</param>
    public static void SugarDataChangedListener(SqlSugarClient db, DiffLogModel diffLogModel)
    {
        var apps = App.EffectiveTypes.Where(u => u.GetInterfaces()
                    .Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarDataChangedListener))));
        var triggerMethodName = "OnChanged";
        foreach (var app in apps)
        {
            var OnChangeMethod = app.GetMethods(BindingFlags.Public | BindingFlags.Instance)
                                                               .Where(u => u.Name == triggerMethodName
                                                                   && u.GetParameters().Length > 0)
                                                               .FirstOrDefault();
            if (OnChangeMethod == null) continue;
            var instance = Activator.CreateInstance(app);
            OnChangeMethod.Invoke(instance, new object[] { db, diffLogModel });
        }
    }

    #endregion 获取数据库连接配置，AOP



    #region 通用方法

    ///// <summary>
    ///// 获取当前租户id
    ///// </summary>
    ///// <returns></returns>
    //private static object GetTenantId()
    //{
    //    if (App.User == null) return null;
    //    return App.User.FindFirst(ClaimConst.Tenant_Id)?.Value;
    //}

    ///// <summary>
    ///// 判断是不是超级管理员
    ///// </summary>
    ///// <returns></returns>
    //private static bool IsSuperAdmin()
    //{
    //    if (App.User == null) return false;
    //    return App.User.FindFirst(ClaimConst.Claim_SuperAdmin)?.Value == UserType.超级管理员.GetHashCode().ToString();
    //}

    /// <summary>
    /// 删除SqlSugar 缓存
    /// </summary>
    /// <typeparam name="TEntity">数据库实体名</typeparam>
    public static void RemoveDataCache<TEntity>()
    {
        try
        {
            var entityInfo = SqlSugarHelper.Db.EntityMaintenance.GetEntityInfo<TEntity>();

            RemoveLikeCache(entityInfo.DbTableName);
        }
        catch (Exception ex)
        {
            var _logger = AppEx.GetLogger("SqlSugar\\删除缓存");
            _logger.Error(ex.ToStringEx());
            throw;
        }
    }

    /// <summary>
    /// 删除包含指定支付查的 SqlSugar 缓存
    /// </summary>
    /// <param name="likeString">相似字符串</param>
    public static void RemoveLikeCache(string likeString)
    {
        try
        {
            // var entityInfo = SqlSugarHelper.Db.EntityMaintenance.GetEntityInfo<TEntity>();
            var cacheKeys = Caches.GetAllCacheKeys("SqlSugarDataCache.");
            foreach (var item in cacheKeys)
            {
                if (item.Contains(likeString))
                {
                    Caches.Remove(item);
                }
            }
        }
        catch (Exception ex)
        {
            var _logger = AppEx.GetLogger("SqlSugar\\删除缓存");
            _logger.Error(ex.ToStringEx());
            throw;
        }
    }

    /// <summary>
    /// 刷新表缓存
    /// </summary>
    /// <returns></returns>
    public static async Task<List<TEntity>> RefreshTableCache<TEntity>()
    {
        var entities = await SqlSugarHelper.Db.Queryable<TEntity>().WithCache().ToListAsync();
        return entities;
    }

    #endregion 通用方法
}